package logserver

import (
	"core/datetime"
	"core/server/baseserver"
	"github.com/dubbogo/gost/log/logger"
	"go.uber.org/zap"

	mylogger "core/logger"
	"os"
	"path/filepath"
	"time"
)

type DeleteLogServer struct {
	baseserver.BaseServer
}

func (p *DeleteLogServer) Start() {
	p.BaseServer.DoInterval = p.DoInterval
	p.BaseServer.Start()
}
func (p *DeleteLogServer) DoInterval() {

	if p.RunTimes%10 != 0 {
		return
	}
	stSeparator := string(filepath.Separator)
	stRootDir, _ := os.Getwd()
	stLogFilePath := stRootDir + stSeparator + "logs"
	err := filepath.Walk(stLogFilePath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			logger.Error("访问文件夹失败:", zap.Error(err))
			return err
		}
		if info.IsDir() {
			return nil
		}
		var fname = info.Name()
		if len(fname) < 10 {
			return nil
		}

		dt, err := datetime.ParseDate(fname[:10])
		if err != nil {
			return nil
		}
		if int(time.Since(dt).Hours()/24) > mylogger.Config.MaxAge {
			err = os.Remove(stLogFilePath + stSeparator + fname)
			if err != nil {
				mylogger.Logger.Error("Delete Log File Error", zap.String("FileName", fname), zap.Error(err))
			} else {
				mylogger.Logger.Info("Delete Log File ", zap.String("FileName", fname))
			}

		}

		return nil
	})
	if err != nil {
		logger.Error("遍历文件夹失败:", zap.Error(err))
	}
}
func init() {
	var r = &DeleteLogServer{baseserver.BaseServer{Name: "删除日志任务", Interval: 60000}}
	r.Start()
}
